using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using WP.Modules;
using WP.DB;
using WP.Commons; 
namespace MaxLeaf
{
    public partial class frmChat : BaseQryRpt 
    {
        public frmChat()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false; 

        }
        public bool IsVisible = false;

        public void ShowMe(bool blnVisible, string strUser, string strMsg,int iRecID)
        {
            if (strMsg == "@Login@")
            {
                this.ShowUser(true);
                return;
            }

            if (strMsg != "" && strUser != "") ShowText(strUser + ":" , strMsg);
            if (iRecID > 0) SaveMsg(strMsg, "", "", ref iRecID);  
            this.ShowUser();
            bool blnFindUser = false;
            foreach (ListViewItem oItem in lstViwUsers.Items)
            {
                if (oItem.Text.Trim().ToUpper() == strUser.ToUpper().Trim())
                {
                    oItem.Checked = true;
                    blnFindUser = true;
                    break;
                }
            }
            if (blnFindUser && this.btnLeft.Text == ">" & !this.IsVisible) this.btnLeft_Click(this, new EventArgs());

            if (blnVisible)
            {
                if (!this.IsVisible) this.Show();
            }
            else
                this.Hide();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtNewMessage.Text.Trim() == "") return; 
                bool blnChecked = false;
                foreach (ListViewItem oItem in lstViwUsers.Items)
                {
                    if (oItem.Checked)
                    {
                        string strIP = oItem.SubItems[2].Text.Trim();
                        int iPort = CvtFunc.ToInt(oItem.SubItems[3].Text);
                        TcpClient tcpClient = new TcpClient(strIP, iPort);
                        NetworkStream ns = tcpClient.GetStream();
                        int iRecID = -1;
                        SaveMsg(txtNewMessage.Text, SysVar.UserName, oItem.SubItems[0].Text.Trim(), ref iRecID);
                        string strMsg = txtNewMessage.Text + "||||" + SysVar.UserName +"||||" + iRecID.ToString()  ;
                        if (oItem.SubItems[4].Text == "True")
                        {
                            ns.Write(Encoding.ASCII.GetBytes(strMsg), 0, strMsg.Length);
                        }
                        ns.Close();
                        tcpClient.Close();
                        blnChecked = true;
                    }
                    else
                    {
                    }
                }
                if (blnChecked)
                {
                    ShowText(SysVar.UserName + ":" , txtNewMessage.Text);
                    txtNewMessage.Text = "";
                    txtNewMessage.Focus();
                }
                else
                {
                    MsgBoxEx.Show(Msg.Select("Please select a user.", DataFunctions.GetMsg(this.Name, "MSG_PleaseSelectUser")), SysVar.WarnTitle);  
                }
            }
            catch (Exception E)
            {
                MsgBoxEx.Show(E.Message, SysVar.WarnTitle);    
            }
        }

        public void NoticeLoginStatusChanged()
        {
           if(!bkWorkerSendMsg.IsBusy)   bkWorkerSendMsg.RunWorkerAsync();  
        }

        private void SaveMsg(string strMsg,string strSendUser,string strSendToUser,ref int iRecID)
        {
            DBAccess dbcon = new DBAccess(false, false);
            if (DataFunctions.CheckRecordExist(dbcon, "mMessageLog", iRecID.ToString(), "RecID"))
                dbcon.ExecuteSql("Update mMessageLog set Received=1 where recid=" + iRecID.ToString());
            else
            {
                DataRow dr = dbcon.GetDataTable("select top 0 * from mMessageLog").NewRow();
                dr["UserName"] = strSendUser;
                dr["UDate"] = DateTime.Today ;
                dr["UTime"] = string.Format("{0:HH:mm}", DateTime.Now);// string.Format("{0:HH:mm:ss}", DateTime.Now);
                dr["SendTo"] = strSendToUser;
                dr["Message"] = strMsg;
                dr["Received"] = false;
                string strFields="UserName,UDate,UTime,SendTo,Message,Received";
                DataFunctions.UpdateTable(dbcon, strFields, "mMessageLog", dr, FormStatus.AddNew);
                iRecID = CvtFunc.ToInt(dr["RecID"]);   
            }
            dbcon.CloseCon();  
        }

        public void ShowText(string strUserInfo, string strMsg)
        {
            if (strMsg.Trim() == "") return;
            txtMessages.AppendText(txtMessages.Text.Trim() != "" ? "\r" : "");

            txtMessages.SelectionLength = 0;
            Font font = new Font("Courier New", 9f, FontStyle.Regular);
            int iSt = txtMessages.Text.Length;
            txtMessages.AppendText(strUserInfo);

            txtMessages.Select(iSt, strUserInfo.Length);
            txtMessages.SelectionFont = font;
            txtMessages.SelectionColor = Color.Black;

            txtMessages.SelectionLength = 0;
            font = new Font("Microsoft Sans Serif", 9f, FontStyle.Regular);
            iSt = txtMessages.Text.Length;
            txtMessages.AppendText(strMsg);

            txtMessages.Select(iSt, strMsg.Length);
            txtMessages.SelectionFont = font;
            txtMessages.SelectionColor = Color.Blue;
            txtMessages.SelectionLength = 0;
        }

        private void ShowUser()
        {
            ShowUser(false);
        }
        private void ShowUser(bool blnRefreshStatus)
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSql = "select a.UserName,isnull(b.ComputerIP,'') as ComputerIP,isnull(b.ComputerName,'') as ComputerName,isnull(b.ComputerPort,'8000') as ComputerPort,isnull(b.Active,0) as Active,cast(0 as bit) as checked from mUser a left join mComputer b on a.UserName= b.UserName order by isnull(b.Active,0)  desc";
            DataView dv = dbcon.GetDataTable(strSql).DefaultView;
            if (blnRefreshStatus)
            {
                foreach (ListViewItem oItem in lstViwUsers.Items)
                {
                    if (!oItem.Checked) continue;
                    dv.RowFilter = "UserName='" + oItem.Text + "'";
                    if (dv.Count > 0)
                    {
                        dv[0].Row["checked"] = true;
                    }
                }
            }
            lstViwUsers.Items.Clear();
            lstViwUsers.View = View.Details;
            lstViwUsers.CheckBoxes = true;
            lstViwUsers.HeaderStyle = ColumnHeaderStyle.None;
            lstViwUsers.Columns.Clear();
            lstViwUsers.Columns.Add("User", 160, HorizontalAlignment.Left);
            lstViwUsers.Columns.Add("CompuerName", 0, HorizontalAlignment.Left);
            lstViwUsers.Columns.Add("IP", 0, HorizontalAlignment.Left);
            lstViwUsers.Columns.Add("Port", 0, HorizontalAlignment.Left);
            lstViwUsers.Columns.Add("Online", 0, HorizontalAlignment.Left);
            dv.RowFilter = "";
            foreach (DataRowView drw in dv)
            {
                ListViewItem oItem = new ListViewItem(drw["Username"].ToString().TrimEnd());
                oItem.SubItems.Add(drw["ComputerName"].ToString().TrimEnd());
                oItem.SubItems.Add(drw["ComputerIP"].ToString().TrimEnd());
                oItem.SubItems.Add(drw["ComputerPort"].ToString().TrimEnd());
                oItem.SubItems.Add(drw["Active"].ToString().TrimEnd());
                if (drw["Active"].ToString().TrimEnd() == "True")
                    oItem.ImageIndex = 0;
                else
                    oItem.ImageIndex = 1;
                oItem.Checked = CvtFunc.ToBoolean(drw["checked"]);
                lstViwUsers.Items.Add(oItem);
            }
            dbcon.CloseCon();
        }

        private void frmChat_Load(object sender, EventArgs e)
        {
            IsVisible = true;
            this.btnHostory_Click(sender, e); 
        }

        private void btnLeft_Click(object sender, EventArgs e)
        {
            if (this.btnLeft.Text == ">")
            {
                this.btnLeft.Text = "<";
                this.txtMessages.Width += this.lstViwUsers.Width;
                this.lstViwUsers.Visible = false;
            }
            else
            {
                this.btnLeft.Text = ">";
                this.txtMessages.Width -= this.lstViwUsers.Width;
                this.lstViwUsers.Visible = true ;
            }
        }

        private void frmChat_FormClosing(object sender, FormClosingEventArgs e)
        {
            IsVisible = false;
            this.Hide(); 
            e.Cancel = true; 
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close(); 
        }

        private void btnHostory_Click(object sender, EventArgs e)
        {
            ShowHistory();
            if(btnHostory.Text.IndexOf("<<")>0)
            {
                btnHostory.Text = "&History>>";
                pnlHistory.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                txtMessages.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                lstViwUsers.Anchor = AnchorStyles.Right | AnchorStyles.Top;
                txtNewMessage.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left;
                btnHostory.Anchor = AnchorStyles.Top | AnchorStyles.Left;
                btnClose.Anchor = AnchorStyles.Top | AnchorStyles.Right;
                btnSend.Anchor = AnchorStyles.Top | AnchorStyles.Right;
                btnClear.Anchor = AnchorStyles.Top | AnchorStyles.Left;

                pnlHistory.Visible = false;
                this.Height -= pnlHistory.Height;
                txtMessages.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                lstViwUsers.Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Top ;
                txtNewMessage.Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left ;
                btnHostory.Anchor = AnchorStyles.Bottom | AnchorStyles.Left ;
                btnClose.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
                btnSend.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
                btnClear.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
                btnClear.Visible = false;
            }
            else
            {
                btnHostory.Text = "&History<<";

                pnlHistory.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                txtMessages.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                lstViwUsers.Anchor = AnchorStyles.Right | AnchorStyles.Top;
                txtNewMessage.Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left;
                btnHostory.Anchor = AnchorStyles.Top | AnchorStyles.Left;
                btnClear.Anchor = AnchorStyles.Top | AnchorStyles.Left;
                btnClose.Anchor = AnchorStyles.Top | AnchorStyles.Right;
                btnSend.Anchor = AnchorStyles.Top | AnchorStyles.Right;

                this.Height +=pnlHistory.Height;
                txtMessages.Anchor =  AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
                lstViwUsers.Anchor =  AnchorStyles.Right | AnchorStyles.Top;
                txtNewMessage.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top;
                btnHostory.Anchor = AnchorStyles.Top | AnchorStyles.Left;
                btnClear.Anchor = AnchorStyles.Top | AnchorStyles.Left;
                btnClose.Anchor = AnchorStyles.Top | AnchorStyles.Right;
                btnSend.Anchor = AnchorStyles.Top | AnchorStyles.Right;
                pnlHistory.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top  ;
                pnlHistory.Visible = true ;
                btnClear.Visible = true ;
            }
        }

        private void ShowHistory()
        {
            txtHistory.Clear(); 
            string strSql = "select * from mMessageLog where ((SendTo='" + SysVar.UserName + "' and Received=1) or UserName='" + SysVar.UserName + "')  and ISSPECIAL=0 order by UDate desc,UTime desc,UserName";
            DBAccess dbcon = new DBAccess(false, false);
            DataView dv = dbcon.GetDataTable(strSql).DefaultView;
            foreach (DataRowView drw in dv)
            {
                txtHistory.SelectionLength = 0;
                Font font= new Font("Courier New",9f, FontStyle.Regular  );  
                string strUserInfo = (txtHistory.Text.Trim() != "" ? "\r" : "") + drw["UserName"].ToString().Trim() + " To " + drw["SendTo"].ToString().Trim() + "(" + BaseFunctions.FormatDate(CvtFunc.ToString(drw["Udate"])) + " " + CvtFunc.ToString(drw["Utime"]) + "):";
                int iSt = txtHistory.Text.Length;
                txtHistory.AppendText ( strUserInfo);
                

                txtHistory.Select(iSt, strUserInfo.Length);
                txtHistory.SelectionFont = font;
                txtHistory.SelectionColor = Color.Black;
                
                txtHistory.SelectionLength = 0;
                font = new Font("Microsoft Sans Serif", 9f, FontStyle.Regular  );
                string strMsg = "\r" + CvtFunc.ToString(drw["Message"]).Trim();
                iSt = txtHistory.Text.Length;
                txtHistory.AppendText(strMsg);

                txtHistory.Select(iSt, strMsg.Length);
                txtHistory.SelectionFont = font;
                txtHistory.SelectionColor = Color.Blue;
                txtHistory.SelectionLength = 0;

            }
            dbcon.CloseCon();  

       }

        private void btnClear_Click(object sender, EventArgs e)
        {
            
            DBAccess dbcon = new DBAccess(false, false);
            if (MsgBoxEx.Show(Msg.Select("Are you sure you want to clear" + "these hisotry", DataFunctions.GetMsg(dbcon, this.Name, "AreYouSureClear", true, new string[] { "these hisotry" })), SysVar.WarnTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                dbcon.CloseCon();
                return;
            }
            string strSql = "delete from mMessageLog where ((SendTo='" + SysVar.UserName + "' and Received=1) or UserName='" + SysVar.UserName + "')  and ISSPECIAL=0";
            dbcon.ExecuteSql(strSql);
            ShowHistory();
        }

        private void bkWorkerSendMsg_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                foreach (ListViewItem oItem in lstViwUsers.Items)
                {
                    try
                    {
                        string strIP = oItem.SubItems[2].Text.Trim();
                        int iPort = CvtFunc.ToInt(oItem.SubItems[3].Text);
                        if (strIP.Trim() == "") continue;
                        if (iPort < 8000) continue;
                        TcpClient tcpClient = new TcpClient(strIP, iPort);
                        NetworkStream ns = tcpClient.GetStream();
                        int iRecID = -1;
                        string strMsg = "@Login@" + "||||" + SysVar.UserName + "||||" + iRecID.ToString();
                        ns.Write(Encoding.ASCII.GetBytes(strMsg), 0, strMsg.Length);
                        ns.Close();
                        tcpClient.Close();
                    }
                    catch
                    {
                        continue;
                    }
                }

            }
            catch(Exception ex)
            {
            }
        }
    }
}